const mysql_query = require("../common/mysql");
const utils = require("../common/utils");
var define = require('../common/define');
const httpresult = require("../common/response");
var logger = require('../common/logger').logger.getLogger("chapter");


async function list(param) {
    let sql = "select * from chapter where course_id = ? ";
    let where_params = [param.course_id];
    if (param.hasOwnProperty("condition") && param.condition.hasOwnProperty("parent_id")) {
        sql += "and parent_id = ?";
        where_params.push(param.condition.parent_id);
    }

    let [error, data] = await mysql_query(sql, where_params);
    if (error) {
        logger.warn(error);
        return [error, null];
    }
    data = data.sort((a, b) => {
        return a.order_number - b.order_number;
    });
    return [null, data];
}

async function get_questions(sql, where_params) {
    var [error, data] = await mysql_query(sql, where_params);
    if (error) {
        return [error, data];
    }
    let questions = [];
    let map = new Map();
    for (let index in data) {
        data[index].description = utils.add_src_host(data[index].description);
        data[index].stem = utils.add_src_host(data[index].stem);
        data[index].analysis = utils.add_src_host(data[index].analysis);
        data[index].answer = utils.add_src_host(data[index].answer);
        data[index].type_name = define.question_type_info[data[index].type];
        // 去重
        if (!map.has(data[index].question_id)) {
            map.set(data[index].question_id, true)
            questions.push(data[index])
        }
    }

    questions = questions.sort((a, b) => {
        return a.order_number - b.order_number;
    });

    return [null, questions];
}
exports.list = list;
exports.get_questions = get_questions;